package com.bwie.service.impl;

import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.TbType;
import com.bwie.service.TbTypeService;
import com.bwie.mapper.TbTypeMapper;
import com.bwie.utils.R;
import com.bwie.vo.TypeInfoVo;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
* @author andy
* @description 针对表【tb_type(商品分类表)】的数据库操作Service实现
* @createDate 2025-07-21 15:23:46
*/
@Service
public class TbTypeServiceImpl extends ServiceImpl<TbTypeMapper, TbType>
    implements TbTypeService{

    @Autowired
    FastFileStorageClient fastFileStorageClient;

    @Override
    public R getTypeList(TypeInfoVo typeInfoVo) {
        //--1 查询所有分类
        QueryWrapper<TbType> wrapper = new QueryWrapper<>();

        if(StringUtils.isNotEmpty(typeInfoVo.getKeyWord())) {
            wrapper.lambda().like(TbType::getTypeName, typeInfoVo.getKeyWord());
        }
        if(typeInfoVo.getTypeStatus() != null) {
            wrapper.lambda().eq(TbType::getTypeStatus, typeInfoVo.getTypeStatus());
        }

        List<TbType> listAll = list(wrapper);

        if(StringUtils.isNotEmpty(typeInfoVo.getKeyWord()) || typeInfoVo.getTypeStatus() != null) {
            return R.OK(listAll);
        }

        //--2 构造树表
        List<Tree<String>> treeList = TreeUtil.build(listAll, "0", (tree, node) -> {
            node.setId("" + tree.getTypeId());
            node.setName(tree.getTypeName());
            node.setParentId("" + tree.getTypePid());

            node.putExtra("typeImage", tree.getTypeImage());
            node.putExtra("typeStatus", tree.getTypeStatus());
            node.putExtra("typeTop", tree.getTypeTop());
            node.putExtra("typeId", tree.getTypeId());
            node.putExtra("typeName", tree.getTypeName());
        });

        return R.OK(treeList);
    }

    @Override
    public R uploadFile(MultipartFile file) {

        try {
            String extName = FileNameUtil.extName(file.getOriginalFilename());
            StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(), extName, null);
            String url = "http://192.168.80.192:8888/" + storePath.getFullPath();
            return R.OK(url);
        } catch (IOException e) {
            //throw new RuntimeException(e);
            return R.ERROR(500, "上传失败");
        }
    }

    @Override
    public R addType(TbType tbType) {

        save(tbType);

        return R.OK();
    }
}




